package com.example.demo.controller;

import com.example.demo.pojo.User;
import com.example.demo.service.IUserService;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import java.util.List;

@SuppressWarnings({"all"})
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @GetMapping("index")//页面的url地址
    public String getindex(Model model)//对应函数
    {
        model.addAttribute("name", "bigsai");
        return "index";//与templates中index.html对应
    }


    @RequestMapping("/detailsForJson")
    public ModelAndView detailsForJson(Integer id) {
        User user = userService.getUser(id);
        ModelAndView mv = new ModelAndView();
        MappingJackson2JsonView jsonView = new MappingJackson2JsonView();
        mv.setView(jsonView);
        mv.addObject("user", user);
        return mv;
    }

    @RequestMapping("/details")
    public String details(Model model, Integer id) {
        User user = userService.getUser(id);
        model.addAttribute("user", user);
        return "details";
    }

    @GetMapping("/add")
    public String add() {
        return "add";
    }

    @PostMapping("/insert")
    @ResponseBody
    public User insert(User user) {
        userService.insertUser(user);
        return user;
    }

    @RequestMapping("/list")
    @ResponseBody
    public List<User> list() {
        //访问模型层得到数据
        List<User> users = userService.findAllUser();
        return users;
    }

    @RequestMapping("/details1")
    public String table0(Model model) {
        List<User> users = userService.findAllUser();
        model.addAttribute("users", users);
        return "details1";
    }

}
